#include <event2/event.h>
#include <event2/listener.h>
#include <iostream>
#include <signal.h>
#include <assert.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
using namespace std;

static const char *ip = "192.168.232.128";
static const int port = 12345;

int main() {
    // 忽略管道信号，避免发送数据给已关闭socket
    if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) {
        cerr << "set pipe signal error" << endl;
        return 1;
    }
    // 创建 libevent 上下文并配置
    event_config *config = event_config_new();

    // 显示支持的网络模式
    const char** methods = event_get_supported_methods();
    cout << "support methods:";
    for (int i = 0; methods[i] != nullptr; i++) {
        cout << methods[i] << " ";
    }
    cout << endl;

    // 设置特征
    event_config_require_features(config, EV_FEATURE_FDS);
    
    // 设置使用 epoll ，采用禁用其他模型的方法：
    event_config_avoid_method(config, "select");
    event_config_avoid_method(config, "poll");

    // 配置 libevent 上下文
    event_base *base = event_base_new_with_config(config);
    event_config_free(config);

    if (base) {
        cout << "create new event base" << endl;
        // 确认特征是否生效
        int feature = event_base_get_features(base);
        cout << "current method is: " << event_base_get_method(base) << endl;
        // 默认是 poll
        if (feature & EV_FEATURE_ET) {
            cout << "EV_FEATURE_ET events supported" << endl;
        } else {
            cout << "EV_FEATURE_ET events not supported" << endl;
        }
        if (feature & EV_FEATURE_O1) {
            cout << "EV_FEATURE_O1 events supported" << endl;
        } else {
            cout << "EV_FEATURE_O1 events not supported" << endl;
        }
        if (feature & EV_FEATURE_FDS) {
            cout << "EV_FEATURE_FDS events supported" << endl;
        } else {
            cout << "EV_FEATURE_FDS events not supported" << endl;
        }
        if (feature & EV_FEATURE_EARLY_CLOSE) {
            cout << "EV_FEATURE_EARLY_CLOSE events supported" << endl;
        } else {
            cout << "EV_FEATURE_EARLY_CLOSE events not supported" << endl;
        }
    } else {
        cerr << "error" << endl;
        return 1;
    }
    // Linux 默认值：
    // EV_FEATURE_ET events supported
    // EV_FEATURE_O1 events supported
    // EV_FEATURE_FDS events not supported
    // EV_FEATURE_EARLY_CLOSE events supported


    // 释放资源
    assert(base);
    event_base_free(base);

}